# -*- coding:utf-8 _*-  
""" 
@author:yanming
@file: setting_interface.py
@version:
@time: 2020/11/22 
@email:476588294@qq.com
@function： 
"""

import os
import re

from PyQt5.QtWidgets import QDialog, QFileDialog, QComboBox, QTableWidgetItem, qApp, QMessageBox
from PyQt5.QtCore import pyqtSlot, Qt
from PyQt5.QtGui import QIcon,QPixmap
from configobj import ConfigObj

from src.config import pdms_table_name, header, authorization_list, user_table_name
from src.setting import Ui_Dialog
from src.database import DataBase
from src.utils import get_user_info
from src.config import setting_radio


class Setting(QDialog, Ui_Dialog):
    def __init__(self):
        super(Setting, self).__init__()
        self.setupUi(self)
        self.connect = DataBase(header, pdms_table_name)
        self.tabWidget.currentChanged['int'].connect(self.tab_data)
        self.config_obj = ConfigObj('config.ini')
        self.lineEditIP.setText(self.config_obj.get('Server').get('ip'))
        self.spinBoxPort.setProperty("value", self.config_obj.get('Server').get('port'))
        self.lineEditIP.textChanged.connect(self.ip_changed)
        self.spinBoxPort.valueChanged.connect(self.port_changed)
        self.pushButtonStartNow.setHidden(True)
        self.pushButtonStartSoon.setHidden(True)
        self.pushButtonConfirm.setHidden(False)
        self.tabWidget.setTabEnabled(2, True)
        self.set_authorization()
        self.set_header_size()

    def set_header_size(self):
        cols = self.tableWidgetSet.columnCount()
        if cols:
            width = 730
            for i in range(cols):
                self.tableWidgetSet.horizontalHeader().resizeSection(i, int(width * setting_radio[i]))

    # 权限设置
    def set_authorization(self):
        hostname, ip, mac = get_user_info()
        cur, db = self.connect.get_connect()
        sql = 'SELECT authorization FROM user WHERE hostname=%s AND ip=%s AND mac=%s'
        cur.execute(sql, [hostname, ip, mac])
        result = cur.fetchall()
        db.close()
        if result:
            if result[0][0] == authorization_list[0]:
                self.tabWidget.setTabEnabled(0, True)
                self.tabWidget.setTabEnabled(1, True)

            else:
                self.tabWidget.setTabEnabled(0, False)
                self.tabWidget.setTabEnabled(1, False)
        else:
            self.tabWidget.setTabEnabled(0, True)
            self.tabWidget.setTabEnabled(1, True)

    # IP修改，则保存到配置文件中
    def ip_changed(self, value):
        self.config_obj['Server']['ip'] = value
        self.config_obj.write()

    # port修改，则保存到配置文件中
    def port_changed(self, value):
        self.config_obj['Server']['port'] = value
        self.config_obj.write()

    # 立即重启按钮槽函数
    @pyqtSlot()
    def on_pushButtonStartNow_clicked(self):
        self.close()
        return qApp.exit(8888)

    # 稍后重启按钮槽函数
    @pyqtSlot()
    def on_pushButtonStartSoon_clicked(self):
        self.close()

    # 加载Excel文件按钮
    @pyqtSlot()
    def on_pushButtonLoad_clicked(self):
        load_path = self.config_obj['path']['load_path']
        select_path = QFileDialog.getExistingDirectory(self, "请选择Excel所在的文件夹", load_path)
        remote_files = self.connect.get_wjm_list()
        if os.path.exists(select_path):
            self.config_obj['path']['load_path'] = select_path
            self.config_obj.write()
            self.lineEditLoad.setText(select_path)
            self.textEdit.setText('开始加载文件数据，请稍等...')
            for index, file in enumerate(os.listdir(select_path)):
                # if re.search("~\\$", file) or not re.search("0\\d-\\d{4}.*\\.(xlsx|xls)$", file):
                if re.search("~\\$", file):
                    self.textEdit.append(
                        '<font color=\"#FF0000\">第{}个文件 --> {} ,加载结果：无效文件</font> '.format(index + 1, file))
                    continue
                if file in remote_files:
                    msg_box = QMessageBox.warning(self, 'Warning', '文件({})已存在，请确认是否替换！'.format(file),
                                                  QMessageBox.Yes | QMessageBox.No)
                    if msg_box == QMessageBox.Yes:
                        cur, db = self.connect.get_connect()
                        sql = "DELETE FROM pdms_data WHERE wjmc=%s"
                        cur.execute(sql, [file])
                        db.commit()
                        db.close()
                        file_path = os.path.join(select_path, file)
                        result = self.connect.write_sql(file_path)
                        if not result:
                            self.textEdit.append(
                                '<font color=\"#00FF00\">第{}个文件 --> {} ,加载结果：重复文件已覆盖</font> '.format(index + 1, file))
                        else:
                            self.textEdit.append('<font color=\"#FF0000\">第{}个文件 --> {} ,加载结果：文件格式有误({})，请确认</font> '
                                                 .format(index + 1, file, result))
                    else:
                        self.textEdit.append(
                            '<font color=\"#00FF00\">第{}个文件 --> {} ,加载结果：重复文件已取消</font> '.format(index + 1, file))
                else:
                    file_path = os.path.join(select_path, file)
                    result = self.connect.write_sql(file_path)
                    if not result:
                        self.textEdit.append(
                            '<font color=\"#00FF00\">第{}个文件 --> {} ,加载结果：加载完成</font> '.format(index + 1, file))
                    else:
                        self.textEdit.append('<font color=\"#FF0000\">第{}个文件 --> {} ,加载结果：文件格式有误({})，请确认</font> '
                                             .format(index + 1, file, result))

        else:
            self.textEdit.setText("源文件路径(%s)有误，请重新配置！！!" % select_path)

    @pyqtSlot()
    def on_pushButtonAdd_clicked(self):
        combobox = QComboBox()
        combobox.setObjectName('QComboBox')
        combobox.addItems(authorization_list)
        combobox.setStyleSheet("QComboBox{background: transparent;}")

        rows = self.tableWidgetSet.rowCount()
        self.tableWidgetSet.insertRow(rows)
        self.tableWidgetSet.setCellWidget(rows, 4, combobox)

    @pyqtSlot()
    def on_pushButtonDelete_clicked(self):
        row_index = self.tableWidgetSet.currentRow()
        if row_index != -1:
            cur, db = self.connect.get_connect()
            ip = self.tableWidgetSet.item(row_index, 2).text()
            del_sql = 'DELETE  FROM user WHERE ip=%s'
            cur.execute(del_sql, [ip])
            db.commit()
            db.close()
            self.tableWidgetSet.removeRow(row_index)

    @pyqtSlot()
    def on_pushButtonConfirm_clicked(self):
        tab_status = self.tabWidget.currentIndex()
        cur, db = self.connect.get_connect()
        if tab_status == 0:
            pass
        else:
            for i in range(self.tableWidgetSet.rowCount()):
                if self.tableWidgetSet.item(i, 0) is None:
                    name = 'None'
                else:
                    name = self.tableWidgetSet.item(i, 0).text()

                if self.tableWidgetSet.item(i, 0) is None:
                    hostname = 'None'
                else:
                    hostname = self.tableWidgetSet.item(i, 1).text()

                if self.tableWidgetSet.item(i, 0) is None:
                    ip = 'None'
                else:
                    ip = self.tableWidgetSet.item(i, 2).text()

                if self.tableWidgetSet.item(i, 0) is None:
                    mac = 'None'
                else:
                    mac = self.tableWidgetSet.item(i, 3).text()

                if self.tableWidgetSet.item(i, 0) is None:
                    authorization = authorization_list[-1]
                else:
                    authorization = self.tableWidgetSet.cellWidget(i, 4).currentText()

                if self.tableWidgetSet.item(i, 0) is None:
                    note = 'None'
                else:
                    note = self.tableWidgetSet.item(i, 5).text()

                search_sql = 'SELECT ip FROM user WHERE ip=%s'
                cur.execute(search_sql, [ip])
                search_result = cur.fetchall()
                if search_result:
                    sql = '''UPDATE user SET user=%s,hostname=%s,mac=%s,authorization=%s,note=%s WHERE ip=%s'''
                else:
                    sql = "INSERT INTO user (user,hostname,mac,authorization,note,ip) VALUES (%s,%s,%s,%s,%s,%s)"
                cur.execute(sql, [name, hostname, mac, authorization, note, ip])

        db.commit()
        db.close()
        self.close()

    # 根据用户权限，配置tab可用情况
    def tab_data(self, index):
        if index == 0:
            self.pushButtonStartNow.setHidden(True)
            self.pushButtonStartSoon.setHidden(True)
            self.pushButtonConfirm.setHidden(False)
        elif index == 1:
            self.pushButtonConfirm.setHidden(False)
            self.pushButtonStartSoon.setHidden(False)
            self.pushButtonStartNow.setHidden(True)
            self.pushButtonStartSoon.setText('取消')
            icon = QIcon()
            icon.addPixmap(QPixmap(":/icon/icon/cancel.svg"), QIcon.Normal, QIcon.Off)
            self.pushButtonStartSoon.setIcon(icon)

            con = DataBase(header, user_table_name)
            cur, db = con.get_connect()
            sql = 'SELECT user,hostname,ip,mac,authorization,note FROM user'
            cur.execute(sql)
            result = cur.fetchall()
            self.tableWidgetSet.setRowCount(len(result))
            for i in range(len(result)):
                for j in range(len(result[i])):
                    item = QTableWidgetItem(str(result[i][j]))
                    item.setTextAlignment(Qt.AlignCenter)

                    if j == 4:
                        combobox = QComboBox()
                        combobox.setObjectName('QComboBox')
                        combobox.addItems(authorization_list)
                        combobox.setCurrentText(result[i][j])
                        combobox.setStyleSheet("QComboBox{background: transparent;}")
                        self.tableWidgetSet.setCellWidget(i, 4, combobox)
                    else:
                        self.tableWidgetSet.setItem(i, j, item)

        else:
            self.pushButtonConfirm.setHidden(True)
            self.pushButtonStartNow.setHidden(False)
            self.pushButtonStartSoon.setHidden(False)
            self.pushButtonStartSoon.setText('稍后重启')
            icon = QIcon()
            icon.addPixmap(QPixmap(":/icon/icon/wait.svg"), QIcon.Normal, QIcon.Off)
            self.pushButtonStartSoon.setIcon(icon)
